# encoding=utf-8

import sys, os
if hasattr(sys, 'frozen'):
    os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']

import PyQt5.QtWidgets as qw
import PyQt5.QtCore as qc
from PyQt5 import QtGui
import ui_main
from PyQt5.QtCore import QTimer, Qt, pyqtSignal
import sys,time
import numpy as np
import random
import json

import threading
import pyqtgraph as pg
import utils
from network import Net_UDP

import ui_home_admin
import ui_set

# 设置网络IP地址信息 窗口
class widgetSet(qw.QWidget, ui_set.Ui_Form):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 如果上次已经配置了，则直接将数据显示在EditLine中，用户可以选择是否重新配置
        self.settings = qc.QSettings("config.ini", qc.QSettings.IniFormat)
        ip = self.settings.value("SETUP/IP_ADDR")
        if (ip):
            self.Edit_ip.insert(ip)
        port = self.settings.value("SETUP/IP_PORT")
        if (port):
            self.Edit_port.insert(port)
        # 绑定信号与槽，点击btn_ensure时候，进入btn_ensure_cb槽函数
        self.btn_ensure.clicked.connect(self.btn_ensure_cb)
    # 槽函数中
    def btn_ensure_cb(self):
        ip = self.Edit_ip.text()
        port = int(self.Edit_port.text())
        print("IP Addr is : %s:%d" % (ip, port))
        self.settings.setValue("SETUP/IP_ADDR", ip)
        self.settings.setValue("SETUP/IP_PORT", port)
        qw.QMessageBox.information(self, "提示", "设置成功")

# 管理界面主窗口
class myWindow(qw.QMainWindow, ui_home_admin.Ui_MainWindow):
    signal_recv_data = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # 曲线图初始化
        pw = pg.PlotWidget(title='Stream Monitor')
        pw.setYRange(0, 100)
        pw.setLabel('bottom','时间')
        pw.setLabel('left','温度')
        pw.showGrid(x=True, y=True)
        self.list_y = []
        self.pl = pw.plot(pen='g')
        self.verticalLayout.addWidget(pw )

        # 下方状态栏信息
        self.statusbar.showMessage("Status : Init")

        # 设置子窗口
        self.w_set = widgetSet()

        # 绑定信号与槽
        self.actionSet.triggered.connect(self.actionSet_cb) # 设置按钮，菜单栏和工具栏中设置是同一个
        self.actionStart.triggered.connect(self.actionStart_cb) # 开始按钮
        self.actionClose.triggered.connect(self.actionClose_cb) # 关闭按钮，停止接收以太网传输过来的UDP数据
        self.actionLogClear.triggered.connect(self.actionClear_cb) # 清除日志
        self.actionLogFind.triggered.connect(self.actionLogFind_cb) #查看日志

        # 设置定时器，定期刷新曲线图数据
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_graph_cb)
        self.timer.start(1000)

        # QSettings初始化，读写配置信息
        self.settings = qc.QSettings("config.ini", qc.QSettings.IniFormat)

        # 自动保存日志
        path = os.getcwd()
        list_files = os.listdir(path)
        if "Log" not in list_files:
            os.system("mkdir Log")
        file_name = "Log/RecvToFile-" + utils.get_current_name() + ".txt"
        self.file = open(file_name, "w+")
        # qw.QMessageBox.information(self, "提示", "save to " + file_name)

        # 全局变量
        self.index_x = 0

        # 实例化UDP类, 将IP地址和端口绑定到套接字上
        self.udp = Net_UDP("192.168.0.111", 8989)
        self.udp_start_flag = 0 # 0：停止接收UDP数据， 1： 接收UDP数据

    def menu_user_cb(self):
        print("Click menu user...........")

    def actionSet_cb(self):
        print("call setup widget.")
        self.w_set.show()

    def actionStart_cb(self):
        ip = self.settings.value("SETUP/IP_ADDR")
        port = self.settings.value("SETUP/IP_PORT")
        if (ip and port):
            self.udp_start_flag = 1
            self.statusbar.showMessage("Status : UDP Start")
        else:
            qw.QMessageBox.warning(self, "提示", "请确认IP地址是否配置OK！")
        
    def actionClose_cb(self):
        self.statusbar.showMessage("Status : UDP Stop")
        self.udp_start_flag = 0

    def actionClear_cb(self):
        self.textBrowser.clear()

    def actionLogFind_cb(self):
        print("Find Log")
        path = os.getcwd() + "/Log"
        filename,_ = qw.QFileDialog.getOpenFileName(self,
                  "选取文件",
                  path,
                  "All Files (*);;Text Files (*.txt)")  #设置文件扩展名过滤,注意用双分号间隔
        text=open(filename,'r').read()
        self.textBrowser.insertPlainText(text)
        

    def update_graph_cb(self):
        if (self.udp_start_flag == 1):
            val, data = self.udp.get_data_from_device()
            if (val != None):
                list_data = list(data)
                show_data = ""
                for item in list_data:
                    show_data = show_data + ("%02x " % item)
                show_data += "\r\n"
                self.file.write(show_data)
                self.textBrowser.insertPlainText(show_data)
                if (self.index_x  <= 50):
                    self.index_x +=1
                    self.list_y.append(val)
                    self.pl.setData(self.list_y)
                else:
                    self.list_y[:-1] = self.list_y[1:]
                    self.list_y[-1] = val
                    self.pl.setData(self.list_y)
                # self.pl.setData(self.index_x, 0)

    def closeEvent(self, event):
        print("close window.................")
        self.file.close()
        event.accept()

if __name__ == "__main__": 
    app = qw.QApplication(sys.argv)
    w = myWindow()
    w.show()

    sys.exit(app.exec_())
